/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.dianlan.test.base;

import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.core.test.TestBase;
import info.peigen.hotpot.component.gateway.core.util.HexUtil;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * <b>(DianlanTestBase)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/8/19
 */
public class DianlanTestBase extends TestBase {
    protected String genBitStr(String... hexStr) {
        String bitStr = HexUtil.hexArrayBinary(hexStr);
        bitStr = StrUtil.replace(bitStr, " ", "");
        return Arrays.stream(StrUtil.split(bitStr, 8)).collect(Collectors.joining());
    }

    protected String append(String... strings) {
        StringBuffer buffer = new StringBuffer();
        for (String string : strings) {
            buffer.append(string);
        }
        return buffer.toString();
    }

    /**
     * 位字符串转字节
     *
     * @param str
     *
     * @return
     */
    protected static byte bitStringToByte(String str) {
        if (null == str) {
            throw new RuntimeException("when bit string convert to byte, Object can not be null!");
        }
        if (8 != str.length()) {
            throw new RuntimeException("bit string'length must be 8");
        }
        try {
            //判断最高位，决定正负
            if (str.charAt(0) == '0') {
                return (byte) Integer.parseInt(str, 2);
            } else if (str.charAt(0) == '1') {
                return (byte) (Integer.parseInt(str, 2) - 256);
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException("bit string convert to byte failed, byte String must only include 0 and 1!");
        }

        return 0;
    }
}